package com.dminvoicemanager;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class DM_Cash_Cheque_ReceiptDetails extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";
	private String SALES_REP_ROUTE = "fRoute";
	private String BANK_DETAILS = "fBank";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Stock Loading
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	private String TEMPSTOCK_ORDER_HEAD = "TempFOrdHed";
	private String TEMPSTOCK_ORDER_DETAIL = "TempFOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";

	// Cash /Cheque Receipt
	private String TEMP_RECEIPT_SUMMARY = "fReceiptSummary";
	private String RECEIPT_HEADER = "fDRecHed";
	private String RECEIPT_DETAILS = "fDRecDet";

	private String RECEIPT_INVOICES = "FDDbNote";

	private SQLiteDatabase mydb;
	Button btnselectcashreceiptinvoice, btnreceiptupdate, btnreceiptreset,btnreceiptauto;
	EditText etdmreceiptinvdate, etdmoriginalamt, etdmoustandamt,
			etdmallocatteamt, etdmbalanceamt, etdmbalamountrec;
	LinearLayout ListCashInvoiceReceiptList, ListCashInvoiceReceiptListDet,
			ListCashInvoiceReceiptSettle;
	String currentUserReceipt, currentUserPrefixLoad, currentUserLocation,
			currentReceiptSerialStr, ReceiptRecordId, ReceiptRefno;
	String treceiptusername, treceiptRefNo, treceiptManualno, detorcode,
			treceiptstartDate, treceiptCusno, treceiptPayType,
			treceiptChequeno, treceiptChequeDate, treceiptBankNo,
			treceiptReceiptAmt, treceiptReceiptBalAmt, treceiptRemark;
	double allocatingAmount = 0.0, outstandingAmount = 0.0,
			balanceAmount = 0.0, newBalanceAmountReceived = 0.0;
	double printBalanceAmount = 0.0, BalAmountReceived = 0.0,
			printBalAmountReceived = 0.0;
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");
	// Print Account Description
	public void AddCashReciptInvoice(View view) {
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		String[] accountdetail = SetTransactionDesc.split("-");
		ReceiptRecordId = accountdetail[0]; // invcuscode
		ReceiptRefno = accountdetail[1]; // invcusname
		Log.v(TAG, "ReceiptRecord Id 1:"+ ReceiptRecordId);
		Log.v(TAG, "Receipt Ref No 2:"+ ReceiptRefno);
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListReceiptsDet = null;
		try {
			curListReceiptsDet = mydb.query(RECEIPT_INVOICES, null,
					"recinv_id='" + ReceiptRecordId + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (curListReceiptsDet != null) {
			if (curListReceiptsDet.getCount() > 0) {
				while (curListReceiptsDet.moveToNext()) {
					String RefNo = curListReceiptsDet.getString(2);
					String RefNo1 = curListReceiptsDet.getString(28);
					String TxnDate = curListReceiptsDet.getString(7);
					String RepCode = curListReceiptsDet.getString(11);
					String Amt = curListReceiptsDet.getString(15);
					String BAmt = curListReceiptsDet.getString(16);
					String RecordId = curListReceiptsDet.getString(1);
					etdmallocatteamt.setEnabled(true);
					btnselectcashreceiptinvoice.setText(RefNo);
					etdmreceiptinvdate.setText(TxnDate);
					
					double AmtVal = Double.parseDouble(Amt.replaceAll("[,]", ""));
					Amt = formatValues.format(AmtVal);
					etdmoriginalamt.setText(Amt);
					
					double BAmtVal = Double.parseDouble(BAmt.replaceAll("[,]", ""));
					BAmt = formatValues.format(BAmtVal);
					etdmoustandamt.setText(BAmt);
					etdmbalanceamt.setText(BAmt);
				}
			}
			else{
				Log.v(TAG, "Receipt Error");
			}
		}
		/*
		 * etdminvcustomer.setText(invcusname);
		 * etdminvcusdis.setText(invcusdiscount);
		 */
		ListCashInvoiceReceiptList.setVisibility(view.GONE);
		ListCashInvoiceReceiptListDet.setVisibility(view.VISIBLE);
		ListCashInvoiceReceiptSettle.setVisibility(view.VISIBLE);
	}

	// Back to Invoice header without selecting Invoice
	public void btnItemsListBack(View view) {
		ListCashInvoiceReceiptList.setVisibility(view.GONE);
		ListCashInvoiceReceiptListDet.setVisibility(view.VISIBLE);
		ListCashInvoiceReceiptSettle.setVisibility(view.VISIBLE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_cash_cheque_receipt_det);

		btnselectcashreceiptinvoice = (Button) findViewById(R.id.btnselectcashreceiptinvoice);
		btnreceiptupdate = (Button) findViewById(R.id.btnreceiptupdate);
		btnreceiptreset = (Button) findViewById(R.id.btnreceiptreset);
		btnreceiptauto= (Button) findViewById(R.id.btnreceiptauto);
		etdmreceiptinvdate = (EditText) findViewById(R.id.etdmreceiptinvdate);
		etdmoriginalamt = (EditText) findViewById(R.id.etdmoriginalamt);
		etdmoustandamt = (EditText) findViewById(R.id.etdmoustandamt);
		// Text change event controller
		etdmallocatteamt = (EditText) findViewById(R.id.etdmallocatteamt);
		etdmallocatteamt.addTextChangedListener(calculateBalanceAmountReceived);

		etdmbalanceamt = (EditText) findViewById(R.id.etdmbalanceamt);
		etdmbalamountrec = (EditText) findViewById(R.id.etdmbalamountrec);

		ListCashInvoiceReceiptList = (LinearLayout) findViewById(R.id.dminvoiceselectReceiptList);
		ListCashInvoiceReceiptListDet = (LinearLayout) findViewById(R.id.dmreceiptinvoicedetailsList);
		ListCashInvoiceReceiptSettle = (LinearLayout) findViewById(R.id.dmlistreciptsettledetList);
		Button StockLoadingData = (Button) findViewById(R.id.btnreceiptback);
		StockLoadingData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Cash_Cheque_Receipt.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "6");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		btnreceiptupdate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				etdmallocatteamt.setEnabled(false);
				checkCashChequeReciptSummary();
			}

		});
		btnreceiptauto.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				etdmallocatteamt.setEnabled(false);
				checkCashChequeReciptSummary();
			}

		});
		btnreceiptreset.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				clearCurrentInvoiceDet();
			}
		});
		
		
		
		currentUserStLoadChk();// Check Current User
		displaybalamtreceived();
	}

	protected void checkCashChequeReciptSummary() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkReceiptSummary = null;
		try {
			chkReceiptSummary = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (chkReceiptSummary != null) {
			if (chkReceiptSummary.getCount() > 0) {
				while (chkReceiptSummary.moveToNext()) {
					treceiptusername = chkReceiptSummary.getString(1);
					treceiptRefNo = chkReceiptSummary.getString(5);
					treceiptManualno = chkReceiptSummary.getString(8);
					treceiptstartDate = chkReceiptSummary.getString(9);
					treceiptCusno = chkReceiptSummary.getString(10);
					treceiptPayType = chkReceiptSummary.getString(12);
					treceiptChequeno = chkReceiptSummary.getString(13);
					treceiptChequeDate = chkReceiptSummary.getString(14);
					treceiptBankNo = chkReceiptSummary.getString(15);
					treceiptReceiptAmt = chkReceiptSummary.getString(17);
					treceiptReceiptBalAmt = chkReceiptSummary.getString(18);
					treceiptRemark = chkReceiptSummary.getString(19);
					// etdmbalamountrec.setText(treceiptReceiptAmt);
					// BalAmountReceived =
					// Double.parseDouble(treceiptReceiptAmt);

					addNewfDReciptDetail();
					//addNewfDReciptHeader();
					UpdateBalanceAmount();
					updatefDDbNote();// Update invoice
				}
			}
		}
	}

	private void UpdateBalanceAmount() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateReceiptBal = null;
		try {
			updateReceiptBal = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		// Update RecordId = ReceiptRecordId
		if (updateReceiptBal != null) {
			if (updateReceiptBal.getCount() > 0) {
				while (updateReceiptBal.moveToNext()) {

					String RecordIdrec = updateReceiptBal.getString(0);
					ContentValues valueupdateReceipt = new ContentValues();
					String amountBalrec = etdmbalamountrec.getText().toString();
					BalAmountReceived = Double.parseDouble(amountBalrec.replaceAll("[,]", ""));
					// BalAmountReceived = printBalanceAmountReceived;
					valueupdateReceipt.put("treceiptReceiptBalAmt",
							amountBalrec);

					Log.v(TAG, "amountBalrec:" + amountBalrec);

					mydb.update(TEMP_RECEIPT_SUMMARY, valueupdateReceipt,
							"tempReceipt_id=" + RecordIdrec, null);
				}
			}
		}
		updateReceiptBal.close();
		mydb.close();
	}

	private void updatefDDbNote() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateReceipt = null;
		try {
			Log.v(TAG, "Update ReceiptRecordId :"+ ReceiptRecordId);
			updateReceipt = mydb.query(RECEIPT_INVOICES, null, "RepCode='"
					+ currentUserReceipt + "' AND recinv_id ='"
					+ ReceiptRecordId + "' AND RefNo ='" +ReceiptRefno+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		// Update RecordId = ReceiptRecordId
		if (updateReceipt != null) {
			if (updateReceipt.getCount() > 0) {
				while (updateReceipt.moveToNext()) {
					String RecordIdrec = updateReceipt.getString(0);
					ContentValues valueupdateReceipt = new ContentValues();
					valueupdateReceipt.put("BAmt", etdmbalanceamt.getText()
							.toString());
					valueupdateReceipt.put("TotBal", etdmbalanceamt.getText()
							.toString());
					mydb.update(RECEIPT_INVOICES, valueupdateReceipt,
							"recinv_id=" + RecordIdrec, null);
				}
			}
		}
		populateOutstandingReceiptList();
		clearCurrentInvoiceDet();
		updateReceipt.close();
		mydb.close();
	}

	private void clearCurrentInvoiceDet() {
		// TODO Auto-generated method stub

		btnselectcashreceiptinvoice.setText("");
		etdmreceiptinvdate.setText("");
		etdmoriginalamt.setText("");
		etdmoustandamt.setText("");
		etdmallocatteamt.setText("0.00");
		etdmbalanceamt.setText("");
		// printUpdatedBalanceAmount();
		// etdmbalamountrec.setText("");
	}

	private void printUpdatedBalanceAmount() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor printReceiptBal = null;
		try {
			printReceiptBal = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		// Update RecordId = ReceiptRecordId
		if (printReceiptBal != null) {
			if (printReceiptBal.getCount() > 0) {
				while (printReceiptBal.moveToNext()) {
					String printReceiptBalStr = printReceiptBal.getString(18);
					
					double printReceiptBalStrVal = Double.parseDouble(printReceiptBalStr.replaceAll("[,]", ""));
					printReceiptBalStr = formatValues.format(printReceiptBalStrVal);
					etdmbalamountrec.setText(printReceiptBalStr);
				}
			}
		}
	}

	private void addNewfDReciptHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues savefDReciptHeader = new ContentValues();
			savefDReciptHeader.put("RefNo", treceiptRefNo);
			savefDReciptHeader.put("ManuRef", treceiptManualno);
			savefDReciptHeader.put("SaleRefNo", "");
			savefDReciptHeader.put("RepCode", treceiptusername);
			savefDReciptHeader.put("TxnType", "40");
			savefDReciptHeader.put("Chqno", treceiptChequeno);
			savefDReciptHeader.put("ChqDate", treceiptChequeDate);
			savefDReciptHeader.put("TxnDate", treceiptstartDate);
			savefDReciptHeader.put("CurCode", "");
			savefDReciptHeader.put("CurRate", "1");
			savefDReciptHeader.put("DebCode", treceiptCusno);
			savefDReciptHeader.put("TotalAmt", treceiptReceiptAmt);
			savefDReciptHeader.put("BTotalAmt", treceiptReceiptAmt);
			savefDReciptHeader.put("BankCur", "");
			savefDReciptHeader.put("BankRate", "1");
			savefDReciptHeader.put("BankAmt", "0");
			savefDReciptHeader.put("BankCharge", "0");
			savefDReciptHeader.put("BBankChg", "0");
			savefDReciptHeader.put("GnLsCal", "");
			savefDReciptHeader.put("DbAcc", treceiptBankNo);
			savefDReciptHeader.put("recipthedSync", "0");
			String[] transType = treceiptPayType.split("-");
			String StrPayType = transType[0]; // invitemskucode
			String StrLocName = transType[1];

			savefDReciptHeader.put("PayType", StrPayType);
			savefDReciptHeader.put("PrtCopy", "0");
			savefDReciptHeader.put("GlPost", "");
			savefDReciptHeader.put("Remarks", treceiptRemark);
			savefDReciptHeader.put("CardSlipNo", "");
			savefDReciptHeader.put("ExpDate", "");
			savefDReciptHeader.put("CrdTypCode", "");
			savefDReciptHeader.put("CCBankAmt", "0");
			savefDReciptHeader.put("GlBatch", "0");
			savefDReciptHeader.put("AddUser", treceiptusername);
			savefDReciptHeader.put("AddMach", "1");
			savefDReciptHeader.put("AddrecDate", getCurrentTimeString()
					.toString());
			mydb.insert(RECEIPT_HEADER, null, savefDReciptHeader);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
	}

	private void addNewfDReciptDetail() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues savefDReciptDetail = new ContentValues();
			savefDReciptDetail.put("RefNo", treceiptRefNo);
			savefDReciptDetail.put("RefNo1", btnselectcashreceiptinvoice
					.getText().toString());
			savefDReciptDetail.put("SaleRefNo", "");
			savefDReciptDetail.put("ManuRef", "");
			savefDReciptDetail.put("TxnType", "40");
			savefDReciptDetail.put("TxnDate", treceiptstartDate);
			savefDReciptDetail.put("DtxnDate", etdmreceiptinvdate.getText()
					.toString());
			savefDReciptDetail.put("DtxnType", "22");
			savefDReciptDetail.put("DCurCode", "");
			savefDReciptDetail.put("DCurRate", "1");
			savefDReciptDetail.put("OCurRate", "1");
			savefDReciptDetail.put("RepCode", treceiptusername);
			savefDReciptDetail
					.put("Amt", etdmallocatteamt.getText().toString());
			savefDReciptDetail.put("BAmt", etdmallocatteamt.getText()
					.toString());
			savefDReciptDetail.put("GainLosAmt", "0");
			savefDReciptDetail.put("BnkChgs", "0");
			savefDReciptDetail.put("BBnkChgs", "0");
			savefDReciptDetail.put("AloAmt", "0");
			savefDReciptDetail.put("OvPayAmt", "0");
			savefDReciptDetail.put("OvPayBal", "0");
			savefDReciptDetail.put("reciptdetSync", "0");
			savefDReciptDetail.put("recsysdate", getCurrentTimeStringCustom().toString());
			
			mydb.insert(RECEIPT_DETAILS, null, savefDReciptDetail);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
	}

	// ***********************************************************************************
	private TextWatcher calculateBalanceAmountReceived = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			/* etdmbalanceamt.setText(""); */
			if (etdmallocatteamt.length() != 0) {
				if (etdmoustandamt.length() != 0
						&& etdmbalanceamt.length() != 0) {
					String etdmoustandamtStr = etdmoustandamt.getText()
							.toString();
					outstandingAmount = Double.parseDouble(etdmoustandamtStr.replaceAll("[,]", ""));
					String etdmbalanceamtStr = etdmbalanceamt.getText()
							.toString();
					balanceAmount = Double.parseDouble(etdmbalanceamtStr.replaceAll("[,]", ""));
					String etdmbalamountrecStr = etdmbalamountrec.getText()
							.toString();
					newBalanceAmountReceived = Double
							.parseDouble(etdmbalamountrecStr.replaceAll("[,]", ""));

					String etdmallocatteamtStr = etdmallocatteamt.getText()
							.toString();
					allocatingAmount = Double.parseDouble(etdmallocatteamtStr.replaceAll("[,]", ""));

					if (allocatingAmount > BalAmountReceived) {
						etdmallocatteamt.setText("0.00");
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Cash_Cheque_ReceiptDetails.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("INVALID ALLOCATING AMOUNT");
						// Setting Dialog Message
						alertDialog
								.setMessage("Allocating Amount Exceed Balanced Received Amount.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
										return;
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}

					double printBalanceAmount = (outstandingAmount - allocatingAmount);
					printBalanceAmount = Math.round(printBalanceAmount * 100) / 100.0d;
					String printBalanceAmountStr = Double
							.toString(printBalanceAmount);
					etdmbalanceamt.setText(printBalanceAmountStr);

					double printBalanceAmountReceived = (BalAmountReceived - allocatingAmount);
					printBalanceAmountReceived = Math
							.round(printBalanceAmountReceived * 100) / 100.0d;
					String printBalanceAmountReceivedStr = Double
							.toString(printBalanceAmountReceived);
					
					double printBalanceAmountReceivedStrVal = Double.parseDouble(printBalanceAmountReceivedStr.replaceAll("[,]", ""));
					printBalanceAmountReceivedStr = formatValues.format(printBalanceAmountReceivedStrVal);
					etdmbalamountrec.setText(printBalanceAmountReceivedStr);

				}
			} else {
				etdmallocatteamt.setText(".00");
				allocatingAmount = 0.00;
			}

		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			allocatingAmount = 0.0;
			// do your stuff

		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			allocatingAmount = 0.0;

		}

	};
	private void displaybalamtreceived() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor balamtreceived = null;
		try {
			balamtreceived = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (balamtreceived != null) {
			if (balamtreceived.getCount() > 0) {
				while (balamtreceived.moveToNext()) {
					detorcode = balamtreceived.getString(10);
					String balamount = balamtreceived.getString(18);
					double balamountVal = Double.parseDouble(balamount.replaceAll("[,]", ""));
					balamount = formatValues.format(balamountVal);
					etdmbalamountrec.setText(balamount);
					
					String balamountP = balamtreceived.getString(18);
					BalAmountReceived = Double.parseDouble(balamountP.replaceAll("[,]", ""));
				}
			}
		}
		populateOutstandingReceiptList();
		balamtreceived.close();
		mydb.close();
	}

	private void populateOutstandingReceiptList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colrecdes_1", "colrecdes_2",
				"colrecdes_3", "colrecdes_4" };
		int[] totrdes = new int[] { R.id.receiptinvrefno, R.id.receiptdate,
				R.id.receiptoutstand, R.id.btnreceiptinvrefno };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListReceiptsOut = null;
		try {
			curListReceiptsOut = mydb
					.query(RECEIPT_INVOICES, null, "DebCode='" + detorcode
							+ "' AND BAmt !='0.00'", null, null, null, null);

		} catch (Exception e) {
		}
		if (curListReceiptsOut != null) {
			if (curListReceiptsOut.getCount() > 0) {
				while (curListReceiptsOut.moveToNext()) {
					String RefNo = curListReceiptsOut.getString(2);
					String RefNo1 = curListReceiptsOut.getString(28);
					String TxnDate = curListReceiptsOut.getString(7);
					String RepCode = curListReceiptsOut.getString(11);
					String Amt = curListReceiptsOut.getString(15);
					String BAmt = curListReceiptsOut.getString(16);
					double BAmtVal = Double.parseDouble(BAmt.replaceAll("[,]", ""));
					BAmtVal = Math.round(BAmtVal * 100) / 100.0d;
					String BAmtValStr = formatValues.format(BAmtVal);
					
					
					
					ReceiptRecordId = curListReceiptsOut.getString(0);

					String columnReceiptdet = ReceiptRecordId + "-" + RefNo;
					HashMap<String, String> maptrdesout = new HashMap<String, String>();
					maptrdesout.put("colrecdes_1", RefNo);
					maptrdesout.put("colrecdes_2", BAmtValStr);
					maptrdesout.put("colrecdes_3", TxnDate);
					maptrdesout.put("colrecdes_4", columnReceiptdet);

					fillMapstrdes.add(maptrdesout);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_cash_cheque_recout_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListReceiptsOut.close();
		mydb.close();
	}

	private void populateCashChequeReceiptList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewReciptInvoiceDetails);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colrecdes_1", "colrecdes_2" };
		int[] totrdes = new int[] { R.id.receiptrefnodet, R.id.receiptrefno };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListReceipts = null;
		try {
			curListReceipts = mydb.query(RECEIPT_INVOICES, null,
					"BAmt !='0.00'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curListReceipts != null) {
			if (curListReceipts.getCount() > 0) {
				while (curListReceipts.moveToNext()) {
					String RefNo = curListReceipts.getString(2);
					String RefNo1 = curListReceipts.getString(28);
					String TxnDate = curListReceipts.getString(7);
					String RepCode = curListReceipts.getString(11);
					String Amt = curListReceipts.getString(15);
					String BAmt = curListReceipts.getString(16);
					String RecordId = curListReceipts.getString(1);

					String columnReceiptdet = RecordId + "/" + RefNo;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colrecdes_1", columnReceiptdet);
					maptrdes.put("colrecdes_2", RefNo);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes,
						R.layout.dm_cash_cheque_receipt_list_raw, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListReceipts.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {
					currentUserReceipt = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(3);
				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// get current data and time
	private String getCurrentTimeStringCustom() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}
}
